using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using EPiServer.Shell.Gadgets;
using EPiServer.Shell.Web;
using EPiServer.Core;
using EPiServer.Research.MobileCenter.JSON;
using EPiServer.Research.MobileCenter.GadgetHelper;
using EPiServer.Web.Hosting;
using System.Web.Hosting;
using EPiServer.Web;
using EPiServer.Research.MobileCenter.Core;
using EPiServer.Configuration.PageGuide;
using EPiServer.Research.MobileCenter.Models;
using EPiServer.Configuration;
using EPiServer.DataAbstraction;


namespace EPiServer.Research.MobileCenter.Examples.Controllers
{
    /// <summary>
    /// Create a news Gadget
    /// </summary>
    [Gadget(IconUrl="/modules/MobileCenterExampleGadgets/Content/Icon2.png", Name="PageGuide", Title="Create pages using Page Guides")]
    [CssResource("/modules/MobileCenterExampleGadgets/Content/createnews.css")]
    public class PageGuideController : MobileCenterJsonBase
    {
        /// <summary>
        /// Gets the page view
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public ActionResult GetPageGuide(string name)
        {
            List<SelectListItem> list = new List<SelectListItem>();

            SelectListItem s1 = new SelectListItem();
            s1.Selected = true;
            s1.Text = "Save and Publish";
            s1.Value = "Save and Publish";

            SelectListItem s2 = new SelectListItem();
            s2.Selected = false;
            s2.Text = "Save";
            s2.Value = "Save";

            list.Add(s1);
            list.Add(s2);
            ViewData.Add("DropDownOptions", list.ToList());

            
            
            //shouldnt do this all the time but only once and then have it in memory
            PageGuideElementCollection pgec = EPiServer.Configuration.Settings.Instance.Parent.PageGuides;

            PageGuideModel model = new PageGuideModel();
            foreach (PageGuideElement pge in pgec)
            {               
                if (pge.Name == name)
                {   
                    model.Name = pge.Name;
                    model.PageTypeName  = pge.PageTypeName;
                    model.Title = pge.Title;
                    model.DestionPageID = pge.DestinationPageId;
                    model.StringProperties = new Dictionary<string,string>();
                    model.XhtmlProperties = new Dictionary<string,string>();
                    
                    PageData pd = DataFactory.Instance.GetDefaultPageData(PageReference.RootPage, pge.PageTypeName);

                    foreach(PagePropertyElement ppe in pge.VisibleProperties)
                    {
                        string propertyName = ppe.PropertyName;

                       
                        var pdata = pd.Property.Where(p => p.Name == propertyName).FirstOrDefault();

                        if (pdata != null)
                        {
                            PageDefinition pagedefintiontype = PageDefinition.Load(pdata.PageDefinitionID);

                            if (pagedefintiontype != null)
                            {
                                if (pagedefintiontype.Type.Name == "XhtmlString")
                                {
                                    model.XhtmlProperties.Add(propertyName, String.Empty);
                                }
                                else if (pagedefintiontype.Type.Name == "String")
                                {
                                    model.StringProperties.Add(propertyName, String.Empty);
                                }
                            }
                            else
                            {
                                model.StringProperties.Add(propertyName, String.Empty);
                            }
                        }

                    }
                    break;
                }
            }

            return View(model); 
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetPageGuide(PageGuideModel PageGuide, string Action)
        {
           
            if (String.IsNullOrEmpty(PageGuide.StringProperties["PageName"]))
            {
                string errormessage = "Page Name is required and cannot be empty";
                ViewData.Add("Error", errormessage);


                return GetPageGuide(PageGuide.Name);
            }
            else
            {
                PageData pd = DataFactory.Instance.GetDefaultPageData(PageReference.Parse(PageGuide.DestionPageID), PageGuide.PageTypeName);
                pd.PageName = PageGuide.StringProperties["PageName"];

                foreach (string propertyname in PageGuide.StringProperties.Keys)
                {
                    pd[propertyname] = PageGuide.StringProperties[propertyname];
                }
                foreach (string propertyname in PageGuide.XhtmlProperties.Keys)
                {
                    pd[propertyname] = PageGuide.XhtmlProperties[propertyname];
                }

                if (Action == "Save and Publish")
                {
                    DataFactory.Instance.Save(pd, EPiServer.DataAccess.SaveAction.Publish);
                }
                else
                {
                    DataFactory.Instance.Save(pd, EPiServer.DataAccess.SaveAction.Save);
                }
                return View("Saved", pd);
            }
        }

        /// <summary>
        /// Gets a value indicating whether [should return list].
        /// </summary>
        /// <value><c>true</c> if [should return list]; otherwise, <c>false</c>.</value>
        public override bool ShouldReturnList
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets the list view.
        /// </summary>
        /// <returns></returns>
        public override List<CellView> GetListView()
        {
              List<CellView> list = new List<CellView>();

            foreach(PageGuideElement element in EPiServer.Configuration.Settings.Instance.Parent.PageGuides){
                CellView c = new CellView();
                c.Name = element.Title;
               
                WebView w = new WebView();
                w.UseDefaultUrl = false;
                w.CustomUrl = GetUrlForView(element.Name);
                w.Name = element.Title;

                c.WebViewToPush = w;
                list.Add(c);
            }

            return list;
            

        }
        /// <summary>
        /// Gets the URL for view.
        /// </summary>
        /// <param name="pageid">The pageid.</param>
        /// <returns></returns>
        public string GetUrlForView(string name)
        {
            return "pageguide/" + name;
        }



        /// <summary>
        /// Gets the web view.
        /// </summary>
        /// <returns></returns>
        public override WebView GetWebView()
        {
            WebView g = new WebView();
            g.Name = "Create News";
            g.UseDefaultUrl = true;
            return g;
        }
      
    }
}
